<?php

namespace App\Model\User;

use App\Common\Tools;
use EasySwoole\ORM\ {
    AbstractModel,
    Utility\Schema\Table,
};
use App\Model\Base;

/**
 * 用户
 * Class User
 */
class User extends Base
{

    protected $tableName = 'auth_user';

    /**
     * 表的字段
     * @return Table
     */
    public function schemaInfo(bool $isCache = true): Table
    {
        $table = new Table($this->tableName);
        $table->colSmallInt('id')->setIsPrimaryKey(true);
        $table->colVarChar('username', 100);
        $table->colVarChar('password', 255);
        $table->colDateTime('last_login');
        $table->colVarChar('last_logip', 50);
        $table->colTinyInt('is_delete');
        /*
        create table auth_user (
            id int(11) auto_increment,
            username varchar(100) comment '登录名',
            password varchar(255) comment '密码，password_hash方法',
            last_login datetime comment '最后登录时间',
            last_logip varchar(50) comment '最后登录ip',
            is_delete tinyint(1) default 0 comment '软删除 0、未删除 1、已删',
            primary key(id)
        ) engine = innodb comment '用户信息';
        */
        return $table;
    }

    /**
     * @description: 范围查询条件
     * @param {*}
     * @return {*}
     */
    public function scopWhere()
    {
        $this->where('is_delete', 0);
        return $this;
    }

    /**
     * @description: 获取未到期的友情链接
     * @param {*}
     * @return {*}
     */
    public function getLinks()
    {
        return static::tryCatch(function() {
            $where = ['expire' => [date('Y-m-d 23:59:59'), '<=']];
        return $this->scopWhere()->where($where)->all()->toArray();
        }, [], []);  
    }

    /**
     * @description: 拼接创建参数
     * @param {*}
     * @return {*}
     */
    protected function createDatas()
    {
        $data = [
            'username'   => $this->param['username'],
        ];
        if (Tools::hasValue($this->param, 'password')) {
            $data['password'] = password_hash($this->param['password'], PASSWORD_DEFAULT);
        }
        return $data;
    }

    /**
     * @description: 分页列表连贯查询
     * @param {*}
     * @return {*}
     */    
    protected function adminPagesCoherent()
    {
        $this->scopWhere();
        return $this;
    }

    /**
     * @description: 列表查询条件默认字段
     * @param {*}
     * @return {*}
     */
    public function nullData()
    {
        return [
            'id'       => '',
            'username' => '',
            'password' => '',
        ];
    }

    /**
     * @description: 分页列表数据处理
     * @param {*}
     * @return {*}
     */    
    protected function adminPagesData($list)
    {
        $datas = $list->toArray();
        foreach ($datas as $key => $val) {
            unset($val['password']);
            $datas[$key] = $val;
        }
        return $datas;
    }
}